import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class leetcode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int i=0;
        List<List<Integer>> ret=new ArrayList<>();
        while(i<nums.length-2){
            if(nums[i]>0) break;
            int left=i+1;
            int right=nums.length-1;
            int a=-nums[i];

            while(left<right){

                List<Integer> list=new ArrayList<>();
                if(nums[left]+nums[right]>a){
                    right--;
                    while(right>left&&nums[right]==nums[right+1]){
                        right--;
                    }
                }else if(nums[left]+nums[right]<a){
                    left++;
                    while(left<right&&nums[left]==nums[left-1]){
                        left++;
                    }
                }else{

                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ret.add(list);
                    System.out.println(nums[i]+":"+nums[left]+":"+nums[right]);
                    right--;
                    while(right>left&&nums[right]==nums[right+1]){
                        right--;
                    }
                    left++;
                    while(left<right&&nums[left]==nums[left-1]){
                        left++;
                    }

                    //System.out.print(nums[i]+":"+nums[left]+":"+nums[right]);
                }
            }

            i++;
            while(i<nums.length-2&&nums[i]==nums[i-1]){
                i++;
            }

        }
        return ret;
    }
}
